package cn.masterj.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.masterj.springcloud.service.IPaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author masterJ
 * @create 2020-04-10 20:40
 */
@Service
public class PaymentServiceImpl implements IPaymentService {

    @Override
    public String payment_ok() {
        return "payment_ok \t" + Thread.currentThread().getName() + IdUtil.simpleUUID();
    }

    @Override
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    },defaultFallback = "fallbackHandler")
    /**
     * @HystrixProperty 里面配置的属性，全在这个类里面找com.netflix.hystrix.HystrixCommandProperties
     */
    public String payment_timeout() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(3000);
        return "payment_timeout \t" + Thread.currentThread().getName() + IdUtil.simpleUUID();
    }

    @Override
//    @HystrixCommand(defaultFallback = "fallbackHandler")
    public String payment_exception() {
        int i = 1/0;
        return "payment_exception \t" + Thread.currentThread().getName() + IdUtil.simpleUUID();
    }

    /**
     * 测试断路，如果满足条件就会打开断路器，服务就会被降级，后续访问这个方法就算是正常访问且无异常也会直接调用fallbackHandler，直到断路器再次关闭
     * 这个断路器 只是针对这个方法打开或关闭，并不是所有的
     * @param id
     * @return
     */
    @Override
    @HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),  //请求次数阈值，默认是20
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),    // 失败次数百分比，60%，默认是50%
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),    // 断路器打开后，重试的等待时间，默认是5秒
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true")    // 打开断路器，默认就是打开的
    },defaultFallback = "fallbackHandler")
    public String payment_circuit(Long id) {
        if (id < 0){
            throw new RuntimeException("id不能小于0");
        }
        return "payment_circuit \t" + Thread.currentThread().getName() + IdUtil.simpleUUID() + "O(∩_∩)O哈哈~\t" + id;
    }


    public String fallbackHandler(Throwable e){
        e.printStackTrace();
        return "我是paymentService的fallbackHandler";
    }
}
